package com.xuebusi.xpress.admin.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Controller
@RequestMapping("py")
public class PyController {

    /**
     * 测试调用python脚本[OK]
     *
     * @param str
     * @return
     */
    @RequestMapping("/hello/{str}")
    @ResponseBody
    public JSONObject hello(@PathVariable("str") String str) {
        JSONObject jsonObject = new JSONObject();
        String[] argsArr = new String[]{"python", "/Users/v_shiyanjun/baidu/ai/xpress/script/refuge-evaluation/hello/hello.py", "Python is best!", str};
        Object result = exec(argsArr);
        jsonObject.put("data", result);
        return jsonObject;
    }

    /**
     * 测试调用python脚本[OK]
     *
     * @return
     */
    @RequestMapping("/demo")
    @ResponseBody
    public JSONObject demo() {
        JSONObject jsonObject = new JSONObject();
        String[] argsArr = new String[]{"python", "/Users/v_shiyanjun/baidu/ai/xpress/script/refuge-evaluation/hello/demo.py", "12", "21"};
        Object result = exec(argsArr);
        jsonObject.put("data", result);
        return jsonObject;
    }

    /**
     * 生成排行榜[测试暂未通过]
     *
     * @return
     */
    @RequestMapping("/genLeaderBoard")
    @ResponseBody
    public JSONObject genLeaderBoard() {
        JSONObject jsonObject = new JSONObject();
        String[] argsArr = new String[]{"python", "/Users/v_shiyanjun/baidu/ai/xpress/script/refuge-evaluation/generate_leaderboards.py"};
        Object result = exec(argsArr);
        jsonObject.put("data", result);
        return jsonObject;
    }

    private Object exec(String[] argsArr) {
        Object result = null;
        try {
            Process proc = Runtime.getRuntime().exec(argsArr);// 执行py文件
            result = read(proc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String read(Process proc) throws IOException, InterruptedException {
        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = in.readLine()) != null) {
            sb.append(line).append(" ");
        }
        in.close();
        proc.waitFor();
        return sb.toString();
    }
}
